package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    //查询所有
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }
    //新增
    @Override
    public void save(Category category) {
        //1.设置id
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        //todo 2.设置操作人
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
//        //设置操作时间
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
        //3.调用mapper
        categoryMapper.save(category);
    }
    //修改
    @Override
    public void update(Category category) {
        //todo 1.设置修改人
//        category.setUpdateUser(1L);
//        //设置修改时间
//        category.setUpdateTime(new Date());
        //2.调用mapper
        categoryMapper.updateById(category);
    }
    //删除
    @Override
    public ResultInfo delete(Long id) {
        //1.调用mapper查询当前分类下的菜品数量
        Integer count1=categoryMapper.countDishByCategoryId(id);
        if (count1 > 0) {
            //return ResultInfo.error("当前分类下还有菜品");
            throw new CustomException("当前分类下还有菜品,不允许删除");
        }
        //2.调用mapper查询当前分类下的套餐数量
        Integer count2=categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0) {
            //return ResultInfo.error("当前分类下还有套餐");
            throw new CustomException("当前分类下还有套餐,不允许删除");
        }
        //3.调用mapper删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }
    //根据type查询分类信息
    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return categoryList;
    }
}
